<?php

namespace App\Console\Commands;

use Illuminate\Console\Command;
use App\Models\CouponRecord;
use GuzzleHttp\Client;
use Carbon\Carbon;

class UpdateCouponRecord extends Command
{
    /**
     * The name and signature of the console command.
     *
     * @var string
     */
    protected $signature = 'cc:upload-coupon-status';

    /**
     * The console command description.
     *
     * @var string
     */
    protected $description = 'Command description';

    /**
     * Create a new command instance.
     *
     * @return void
     */
    public function __construct()
    {
        parent::__construct();
    }

    protected function getGuzzleClient()
    {
        return new Client(['Content-Type' => 'application/json']);
    }
    /**
     * Execute the console command.
     *
     * @return int
     */
    public function handle()
    {

         $records = CouponRecord::query()->where("status",'unused')->where("expired_at",">",date("Y-m-d H:i:s",time()))->get();

         if($records->isEmpty()){

            return false;
         }else{

            foreach($records as $record){

                if(empty($record->qrcode_url)){
                    continue;
                }else{

                    $queryString = parse_url($record->qrcode_url, PHP_URL_QUERY);
                    parse_str($queryString, $params);

                    $punitId = $params['punitId']; // "21923"
                    $iden = $params['iden']; // "K34r6oV3tk4VI27D5X3"

                    $params = [
                        'punitId'=>$punitId,
                        'iden'=>$iden,
                    ];
                    $result = $this->getGuzzleClient()->post("https://wx.deliyun.cn/apis/shop/wx/findShopQRCouponsByIden", ['json' =>$params ])->getBody()->getContents();

                    $result = json_decode($result,true);
                    if($result['data']['state']==1){

                        $record->update(["status"=>"used",'used_at'=>Carbon::now()]);
                    }
                }
            }
         }

    }
}
